<template>
  <el-select 
    v-model="modelValue" 
    placeholder="请选择物料" 
    clearable 
    filterable 
    @change="onChange" 
    style="width: 100%;"
    :loading="loading"
    remote
    :remote-method="searchMaterials"
    :reserve-keyword="true"
  >
    <el-option
      v-for="item in filteredOptions"
      :key="item.id"
      :label="`${item.materialName}（${item.materialCode}）`"
      :value="item.id"
    />
  </el-select>
</template>
<script setup lang="ts">
import { MaterialInfoApi } from '@/api/oa/materialinfo'
import type { MaterialInfoVO } from '@/api/oa/materialinfo'

const props = defineProps<{
  modelValue: number | undefined,
  options: any[]
}>()
const emit = defineEmits(['update:modelValue'])

const modelValue = computed({
  get: () => props.modelValue,
  set: v => emit('update:modelValue', v)
})

const loading = ref(false)
const filteredOptions = ref<MaterialInfoVO[]>([])

// 远程搜索物料方法
const searchMaterials = async (query: string) => {
  if (query === '') {
    // 如果搜索词为空，显示所有选项
    filteredOptions.value = props.options
    return
  }
  
  loading.value = true
  try {
    // 同时搜索物料编码和物料名称，后端支持模糊搜索
    const res = await MaterialInfoApi.getMaterialInfoPage({ 
      pageNo: 1, 
      pageSize: 50,
      materialCode: query,
      materialName: query
    })
    
    filteredOptions.value = res.list || []
  } catch (error) {
    console.error('搜索物料失败:', error)
    filteredOptions.value = []
  } finally {
    loading.value = false
  }
}

// 监听options变化，初始化filteredOptions
watch(() => props.options, (newOptions) => {
  filteredOptions.value = newOptions
}, { immediate: true })

function onChange(val: number) {
  emit('update:modelValue', val)
}
</script> 